﻿namespace compileawaitasync
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //await DownHtmlAsync("https://www.baidu.com", @"d:\test\2.txt");
            int L = await DownHtmlAsync1("https://www.baidu.com", @"d:\test\3.txt");
            await Console.Out.WriteLineAsync("ok" + L);
        }

        /// <summary>
        /// 无返回值
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        static async Task DownHtmlAsync(string url, string filename)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                string html = await httpClient.GetStringAsync(url);
                await File.WriteAllTextAsync(filename, html);
            }
        }

        /// <summary>
        /// 有返回值
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        static async Task<int> DownHtmlAsync1(string url, string filename)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                string html = await httpClient.GetStringAsync(url);
                await File.WriteAllTextAsync(filename, html);
                return html.Length;
            }
        }

        /// <summary>
        /// 对于不支持异步方法的，按照如下分解
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static async Task DownHtmlAsync2(string filename)
        {
            //有返回值
            Task<string> t = File.ReadAllTextAsync(filename);
            string s = t.Result;
            //无返回值
            File.WriteAllTextAsync(filename, "sssssss").Wait();
        }

        /// <summary>
        /// 异步委托 线程池
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static async Task s(string filename)
        {
            ThreadPool.QueueUserWorkItem(async (obj) =>
            {
                await File.WriteAllTextAsync(filename, "sssssss");
            });
        }
    }
}